function Mout=BinImg2d(Min,bindims)
%BinImg2d - simple tool for 2D downsampling
%
% M=BinImg2d(M,bindims)
%
%in:
%
% M: a matrix
% bindims: a vector [p,q] specifying pxq downsampling
%
%out:
%
% M: the downsized matrix

[m,n,d]=size(Min); %M is the original matrix
p=bindims(1); q=bindims(2);

if mod(m,p)~=0 || mod(n,q)~=0
    %p=floor(p+(mod(m,p)/floor(m/p)));
    %q=floor(q+(mod(n,q)/floor(n/q)));
    p=2^nextpow2(p);
    q=2^nextpow2(q);
    warning('Unusable bin size. Bin size used: (%d,%d)',p,q)
end
Mout=zeros(m/p,n/q,d);
for i=1:d
    Mtemp=Min(:,:,i);
    Mtemp=sum( reshape(Mtemp,p,[]) ,1 );
    Mtemp=reshape(Mtemp,m/p,[]).'; %Note transpose
    
    Mtemp=sum( reshape(Mtemp,q,[]) ,1);
    Mtemp=reshape(Mtemp,n/q,[]).'; %Note transpose
    
    Mtemp=Mtemp/(p*q);
    Mout(:,:,i)=Mtemp;
end


